var inquirer = require('inquirer');
const chalk = require('chalk');
const ora = require('ora');
const { exec } = require('child_process');
var fs = require("fs");
let path = require('path');
const spinner = ora();
let GLOBAL_ESLINTRC_PATH = path.resolve(__dirname, '../.eslintrc.js');
const LOCAL_ESLINTRC_FILENAME=['.eslintrc.js', '.eslintrc.yaml', '.eslintrc.yml', '.eslintrc.json', '.eslintrc']; //注意顺序不要变
/**
 * 判断本地是否存在eslint配置
 */
async function getFieldPath(pathList){
    const checkPath = function(path){
        return new Promise((resolve, reject)=>{
            fs.access(`./${path}`, fs.constants.F_OK,function(error){
                if(error){
                    resolve(false);
                }else{
                    resolve(true);
                }
            });
        });
    } 
    
    let path = '';
    for (let index = 0; index < pathList.length; index++) {
        path = pathList[index];
        let exist = await checkPath(path);
        if(exist){
            break;
        }else{
            path = '';
        }
    }
    return path;
}

/**
 * 执行项目自身eslint
 */
function handleLocalConfig(cmd,src){
    spinner.start();
    spinner.text = chalk.green(`正在执行 eslint`);
    //这里必须要使用项目内的eslint，用全局安装的会报错，详见readme
    let cmdStr = `./node_modules/.bin/eslint ${cmd.fix?'--fix':''} ${src}`;
    exec(cmdStr,{
       cwd: process.cwd(),
       shell: '/bin/sh', //TODO:待验证是否有用
    }, (error,stdout,stderr) => {
        //不要在这里判断error，eslint的输出会触发error
        if (stdout) {
            spinner.info('执行完成，输出如下：\n');
            console.log(chalk.white(stdout))
            process.exit()
        }
    })
}

/**
 * 执行全局eslint
 */
async function handleStandardConfig(cmd,src){
    spinner.start();
    spinner.text = chalk.green(`正在执行 eslint`);
    //全局eslint执行全局配置
    src = path.join(process.cwd(), src)
    let cmdStr = `npm run eslint -- -c ${GLOBAL_ESLINTRC_PATH} ${cmd.fix?'--fix':''} ${src}`;
    exec(cmdStr, {
        cwd: __dirname,
    }, (error,stdout,stderr) => {
        spinner.info('执行完成，输出如下：\n');
        console.log(chalk.white(stdout))
        process.exit()
    })
}

/**
 * 主入口
 */
async function main(cmd,src){
    // 先判断当前文件是否有eslint文件; 
    // 暂不考虑package.eslintConfig; 也不考虑自定义名称的
    const configPath = await getFieldPath(LOCAL_ESLINTRC_FILENAME);
    
    // 再判断入口文件
    // 当前写法只支持文件或文件夹，不支持正则
    src = src || 'src';
    const srcPath = await getFieldPath([`${src}`]);

    inquirer.prompt([
        {
            type:"rawlist",
            message:"请选择eslint规则？",
            name:'file',
            choices:[{
                'value': 'locally',
                'name': `当前项目的配置文件${configPath}`
            },{
                'value': 'globally',
                'name': `cli统一配置文件`
            }],
            default:"globally",
            pageSize:10,
            when: !!configPath,
        },
        {
            type: 'input',
            message: `未检测到${src},请输入入口文件?`,
            name: 'src',
            when: !srcPath,
        }
    ]).then(answers=>{
        let file = answers.file || "globally";
        let src = srcPath || answers.src;
        switch (file) {
            case "locally":
                handleLocalConfig(cmd,src);
                break;
            case "globally":
                handleStandardConfig(cmd,src);
                break;
            default:
                break;
        }
    })
}
module.exports = main;